package com.honey.mybatis.generator.mappper;

import java.util.List;

import com.honey.compilation.xml.XmlElement;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.Column;
import com.honey.core.dbmapping.structure.Schema;
import com.honey.core.dbmapping.structure.Table;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.mybatis.generator.MybatisPlugin;

public class Insert extends AbstractMybatisMapper{

	public Insert(MybatisPlugin belongPlugin) {
		super(belongPlugin);
	}

	public void appendElement(XmlElement parent, Schema schema, IntrospectSchemaColumn introspectSchemaColumn ){
		IntrospectTableColumn introspectTableColumn = null;
		if( schema instanceof Table ){
			introspectTableColumn = (IntrospectTableColumn)introspectSchemaColumn;
		}else{
			return ;
		}
		
		parent.addNewLine();
		parent.addComments(
				"插入新的记录,不包含大字段."
		);
		XmlElement insert = new XmlElement(parent,"insert")
		.addAttribute("id",MapperConstant.INSERT_MAPPER_ID)
		.addAttribute("parameterType",super.getEntityPrimitiveClassType(schema).getLongName())
		.addAttribute("timeout", mybatisPlugin.getConnectionTimeOut())
		.addAttribute("flushCache", "true")
		.addAttribute("useGeneratedKeys", "true")
		.addTextElement("INSERT INTO " + schema.getName())
		;
		
		List<TableColumn> list = introspectTableColumn.primaryKeyColumns();
		StringBuilder sb = new StringBuilder();
		boolean comma = false;
		for(TableColumn column : list ){
			if(comma) sb.append(",");else comma = true;
			sb.append(column.getJavaProperty());
		}
		insert.addAttribute("keyProperty", sb.toString());
		sb.setLength(0);
		
		StringBuilder values = new StringBuilder();
		List<Column> columns = introspectTableColumn.allColumns();
		String modelPackage = super.getModelPrimitiveClassType(schema).getLongName();
		sb.append("(");values.append("(");
		comma = false;
		for(Column column : columns ){
			TableColumn tc =(TableColumn)column;
			if(tc.isPrimaryKey() || tc.isBLOBColumn() ) continue;
			
			if(comma){sb.append(",");values.append(",");}else comma = true;
			sb.append(tc.getName());
			values.append("#{").append(super.getFieldName(column)).append(",jdbcType=").append(JdbcTypeName.getJdbcTypeName(tc.getJdbcType()));
			if( column.getEnumSchema() != null){
				values.append(",typeHandler=").append(modelPackage);
			}
			values.append("}");
			
		}
		sb.append(")");values.append(")");
		insert.addTextElement(sb.toString());
		insert.addTextElement("VALUES");
		insert.addTextElement(values.toString());
	}
}
